package com.wosai.teach.fragment;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.agnetty.constant.HttpCst;
import com.android.agnetty.core.AgnettyFutureListener;
import com.android.agnetty.core.AgnettyResult;
import com.android.agnetty.future.http.HttpFuture;
import com.wosai.teach.R;
import com.wosai.teach.activity.ExpDetailAction;
import com.wosai.teach.adapter.HallAdapter;
import com.wosai.teach.adapter.NewPagerAdapter;
import com.wosai.teach.dao.ExperimentDao;
import com.wosai.teach.dao.InstallDao;
import com.wosai.teach.dialog.NewProgressDialog;
import com.wosai.teach.handler.ExperimentListHandler;
import com.wosai.teach.handler.InstallHandler;
import com.wosai.teach.handler.MessageLoginHallHandler;
import com.wosai.teach.handler.PicLoginHallHandler;
import com.wosai.teach.listener.NewPageChangeListener;
import com.wosai.teach.pojo.Experiment;
import com.wosai.teach.pojo.Install;
import com.wosai.teach.pojo.Pic;
import com.wosai.teach.thread.DownloadFactory;
import com.wosai.teach.thread.LunBoRunnable;
import com.wosai.teach.utils.AppCst;
import com.wosai.teach.utils.AppGlobal;
import com.wosai.teach.utils.C;
import com.wosai.teach.utils.CustomMarqueeTextView;
import com.wosai.teach.utils.FixedSpeedScroller;
import com.wosai.teach.utils.GodUtils;
import com.wosai.teach.utils.ImageLoaders;

/**
 * @author : qiumy
 * @e-mail : qiumy@wosaitech.com
 * @date : 2015-3-31 下午4:41:16
 * @desc : 教学仿真大厅
 */
public class HallFragment extends Fragment implements OnClickListener {
	// http://blog.csdn.net/wocao1226/article/details/8980368 安装APP总结
	private ExperimentDao experimentDao;
	private List<Experiment> expList;
	private List<Pic> picList;
	private View view;

	private ListView listMsg;
	private HallAdapter adapter;
	private LinearLayout car_ll;
	private ViewGroup viewGroup;
	private ViewPager viewPager;
	private LunBoRunnable runnable;
	private NewProgressDialog progressdialog;
	private CustomMarqueeTextView marquee_textview;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.frag_hall, null);
		this.initFactory();
		initView(view);
		loadSoftInfo();
		return view;
	}

	private void initFactory() {
		AppGlobal.factory = new DownloadFactory(getActivity());
		if (AppGlobal.instHandler == null) {
			AppGlobal.instHandler = new InstallHandler();
		}
		AppGlobal.instHandler.setCurAct(this);
	}

	private void loadSoftInfo() {
		progressdialog = NewProgressDialog.showProgress(getActivity(),
				"正在获取仿真信息...", false);
		String url = AppCst.HTTP_URL_EXPERIMENT_LIST;
		int userId = 0;
		if (AppGlobal.user != null) {
			userId = AppGlobal.user.getUserId();
		}
		url = url.replace("{userId}", userId + "");
		System.out.println(url);
		new HttpFuture.Builder(getActivity(), HttpCst.GET).setUrl(url)
				.setHandler(ExperimentListHandler.class)
				.setListener(new AgnettyFutureListener() {
					@Override
					public void onComplete(AgnettyResult result) {
						super.onComplete(result);
						refresh();
					}

					@Override
					public void onException(AgnettyResult result) {
						super.onException(result);
						refresh();
					}
				}).execute();
		// 获取轮播图片
		String url2 = AppCst.HTTP_URL_PIC_LOGIN_HALL;
		url2 = url2.replace("{userId}", userId + "");
		url2 = url2.replace("{pageSize}", 5 + "");
		url2 = url2.replace("{currentPage}", 1 + "");
		System.out.println(url2);
		new HttpFuture.Builder(getActivity(), HttpCst.GET).setUrl(url2)
				.setHandler(PicLoginHallHandler.class)
				.setListener(new AgnettyFutureListener() {
					@Override
					public void onComplete(AgnettyResult result) {
						super.onComplete(result);
						Object rst = result.getAttach();
						picList = (List<Pic>) rst;
						exeCar();
					}

					@Override
					public void onException(AgnettyResult result) {
						super.onException(result);
						exeCar();
					}
				}).execute();
		// 获取走马灯文字
		String url3 = AppCst.HTTP_URL_MESSAGE_LOGIN_HALL;
		url3 = url3.replace("{userId}", userId + "");
		url3 = url3.replace("{pageSize}", 5 + "");
		url3 = url3.replace("{currentPage}", 1 + "");
		System.out.println(url3);
		new HttpFuture.Builder(getActivity(), HttpCst.GET).setUrl(url3)
				.setHandler(MessageLoginHallHandler.class)
				.setListener(new AgnettyFutureListener() {
					@Override
					public void onComplete(AgnettyResult result) {
						super.onComplete(result);
						Object rst = result.getAttach();
						marquee_textview.setText((String) rst);
					}

					@Override
					public void onException(AgnettyResult result) {
						super.onException(result);
					}
				}).execute();
	}

	private void initView(View view) {
		TextView title = (TextView) view.findViewById(R.id.title);
		title.setText("仿真教育平台");
		Button refresh = (Button) view.findViewById(R.id.refresh);
		refresh.setOnClickListener(this);
		listMsg = (ListView) view.findViewById(R.id.teach_list);
		listMsg.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Experiment exp = (Experiment) adapter.getItem(position);
				Intent it = new Intent(getActivity(), ExpDetailAction.class);
				Bundle bd = new Bundle();
				bd.putSerializable("exp", exp);
				it.putExtras(bd);
				getActivity().startActivity(it);
			}
		});

		car_ll = (LinearLayout) view.findViewById(R.id.car_ll);
		viewPager = (ViewPager) view.findViewById(R.id.car_vp);
		viewGroup = (ViewGroup) view.findViewById(R.id.car_vg);
		marquee_textview = (CustomMarqueeTextView) view
				.findViewById(R.id.marquee_textview);
		this.refresh();
	}

	private void refresh() {
		experimentDao = new ExperimentDao();
		expList = experimentDao.findAllExperiment();
		adapter = new HallAdapter(getActivity(), this, expList);
		listMsg.setAdapter(adapter);
		if (progressdialog != null) {
			progressdialog.dismiss();
		}
	}

	/**
	 * 轮播，活动
	 */
	private void exeCar() {
		this.car_ll.setVisibility(View.VISIBLE);
		LayoutInflater layIn = LayoutInflater.from(getActivity());
		List<View> viewList = new ArrayList<View>();
		if (GodUtils.CheckNull(picList)) {
			int[] cars = { R.drawable.car1, R.drawable.car2, R.drawable.car3 };
			for (int car : cars) {
				View view = layIn.inflate(R.layout.activity_lun_item,
						viewPager, false);
				ImageView iv = (ImageView) view.findViewById(R.id.lun_iv);
				iv.setImageResource(car);
				iv.setScaleType(ScaleType.FIT_XY);
				viewList.add(view);
			}
		} else {
			for (Pic pic : picList) {
				View view = layIn.inflate(R.layout.activity_lun_item,
						viewPager, false);
				ImageView iv = (ImageView) view.findViewById(R.id.lun_iv);
				ImageLoaders.getInstance().displayImage(iv, pic.getUrl());
				iv.setScaleType(ScaleType.FIT_XY);
				viewList.add(view);
			}
		}

		NewPagerAdapter adapter = new NewPagerAdapter(viewList);
		viewPager.setAdapter(adapter);

		FixedSpeedScroller scroller = null;
		try {
			Field mField = ViewPager.class.getDeclaredField("mScroller");
			mField.setAccessible(true);
			scroller = new FixedSpeedScroller(viewPager.getContext(),
					new AccelerateInterpolator());
			mField.set(viewPager, scroller);
		} catch (Exception e) {
			e.printStackTrace();
		}

		ImageView[] imageViews = new ImageView[viewList.size()];
		for (int i = 0; i < viewList.size(); i++) {
			ImageView imageView = new ImageView(getActivity());
			imageView.setLayoutParams(new LayoutParams(36, 16));
			imageView.setPadding(10, 0, 10, 0);// 左 上 右 下
			imageViews[i] = imageView;
			if (i == 0) {
				// 默认选中第一张图片
				imageViews[i].setImageResource(R.drawable.point_white);
			} else {
				imageViews[i].setImageResource(R.drawable.point_grey);
			}
			viewGroup.addView(imageViews[i]);
		}
		NewPageChangeListener listener = new NewPageChangeListener(imageViews);
		viewPager.setOnPageChangeListener(listener);

		Handler handler = new Handler();
		runnable = new LunBoRunnable(viewPager, viewList.size(), handler);
		runnable.setScroller(scroller);
		handler.postDelayed(runnable, 4000);
	}

	@Override
	public void onResume() {
		super.onResume();
		AppGlobal.instHandler.setCurAct(this);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.refresh:
			loadSoftInfo();
			break;
		}
	}

	public HallAdapter getAdapter() {
		return adapter;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == C.REQUEST_CODE_UPDATE
				|| requestCode == C.REQUEST_CODE_INSTALL) {
			// 成功
			for (Experiment exp : expList) {
				if (AppGlobal.curInstExpId == exp.getExpId()) {
					exp.initNative(getActivity());
					if (exp.getVersionCode() >= 1) {
						exp.setStatus(C.TEACH_STATUS_INSTALL);
						ExperimentDao expDao = new ExperimentDao();
						expDao.saveOrUpdateExp(exp);
						InstallDao instDao = new InstallDao();
						Install inst = instDao
								.getInstallByExpId(exp.getExpId());
						inst.delete();
					}
				}
			}
		}
		adapter.notifyDataSetChanged();
	}
}
